package com.pi.base.interceptor;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.alibaba.fastjson.JSONObject;
import com.pi.base.common.BaseResult;
import com.pi.base.constant.SysStatics;
import com.pi.base.entity.SysUser;

public class LoginInterceptor extends HandlerInterceptorAdapter{
	
	private final Logger logger = LoggerFactory.getLogger(LoginInterceptor.class);
	
	 @Override    
	    public boolean preHandle(HttpServletRequest request,    
	            HttpServletResponse response, Object handler) throws Exception {  
		 logger.info("==============执行顺序: 1、preHandle================");
		 logger.info("访问接口："+request.getRequestURI());
		 // 过滤社区接口
		 if(!StringUtils.isBlank(request.getRequestURI()) && request.getRequestURI().indexOf("/community/adduser") > 0){
		 	return true;
		 }
		 SysUser loginUser =  (SysUser) request.getSession().getAttribute(SysStatics.WEB_USER_SESSION);
		 logger.info("loginUser:"+loginUser);
		 if(loginUser == null){
			if (!isAjaxRequest(request)) {
				// 跳回主页
				request.getRequestDispatcher("/WEB-INF/view/system/error/blank.jsp").forward(
						request, response);
				return false;
			} else {
				BaseResult result = new BaseResult(BaseResult.STATUS_NOLOGIN);
				 PrintWriter writer = response.getWriter(); 
		         writer.write(JSONObject.toJSONString(result)); 
		         writer.flush(); 
		         return false;
			}
			// throw new SessionTimeoutException();
		 }
		 logger.info("loginUser:"+loginUser.getUsername());
		  return true;
	 }
	 
	 
	 private boolean isAjaxRequest(HttpServletRequest request){
		  if (request.getHeader("accept").indexOf("application/json") > -1
		             || (request.getHeader("X-Requested-With")!= null && request.getHeader("X-Requested-With").indexOf("XMLHttpRequest") > -1)) {
			  return true;
		  }else{
			  return false;
		  }
	 }
	 
	 
	 
	 /** 
	     * 在业务处理器处理请求执行完成后,生成视图之前执行的动作    
	     * 可在modelAndView中加入数据，比如当前时间 
	     */  
	    @Override    
	    public void postHandle(HttpServletRequest request,    
	            HttpServletResponse response, Object handler,    
	            ModelAndView modelAndView) throws Exception {     
	       // logger.info("==============执行顺序: 2、postHandle================");    
	        //logger.info(modelAndView.getViewName());
	    }    
	    
	    /**  
	     * 在DispatcherServlet完全处理完请求后被调用,可用于清理资源等   
	     *   
	     * 当有拦截器抛出异常时,会从当前拦截器往回执行所有的拦截器的afterCompletion()  
	     */    
	    @Override    
	    public void afterCompletion(HttpServletRequest request,    
	            HttpServletResponse response, Object handler, Exception ex)    
	            throws Exception {    
	     //   logger.info("==============执行顺序: 3、afterCompletion================");    
	    }    
	  

}
